package com.summer.patterns;

import java.util.LinkedList;

public class TaskCenter {

    private TaskStatus taskStatus = TaskStatus.ready;
    private LinkedList<TaskBase> taskList = new LinkedList<>();
    
    private OnTaskCenterCompleteListener onTaskCenterCompleteListener;
    
    public TaskCenter addTask(TaskBase taskBase) throws RuntimeException{
        if(taskStatus != TaskStatus.ready){
            throw new RuntimeException();
        }
        taskBase.bindTaskCenter(this);
        taskList.add(taskBase);
        return this;
    }

    public void execute(){
    	if(taskStatus == TaskStatus.done){
            error();
            return;
    	}
        for(TaskBase taskBase : taskList){
        	if (taskBase.prepare()) {
                taskList.remove(taskBase);
                taskBase.doTask();
                return;
            }
        }
        success();
    }

    public void error(){
        taskStatus = TaskStatus.done;
        if(onTaskCenterCompleteListener != null){
            onTaskCenterCompleteListener.onError();
        }
    }

    public void success(){
        taskStatus = TaskStatus.done;
        if(onTaskCenterCompleteListener != null){
            onTaskCenterCompleteListener.onSuccess();
        }
    }

    public interface OnTaskCenterCompleteListener{
        public void onSuccess();
        public void onError();
    }
}
